package com._520it.smis.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com._520it.smis.dao.IStudentDao;
import com._520it.smis.domian.Student;
import com._520it.util.JdbcUtil;

public class StudentDaoImpl implements IStudentDao {

	@Override
	public void save(Student newStu) {
		String sql = "INSER INTO t_student VALUES (?,?)";
		Connection coon = null;
		PreparedStatement ps = null;
		coon = JdbcUtil.getConn();
		try {
			ps = coon.prepareStatement(sql);
			ps.setString(1, newStu.getName());
			ps.setInt(2, newStu.getAge());
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(coon, ps, null);
		}
	}

	@Override
	public void delete(Long id) {
		String sql = "DELETE FROM t_student WHERE id = ?";
		Connection coon = null;
		PreparedStatement ps = null;
		try {
			coon = JdbcUtil.getConn();
			ps = coon.prepareStatement(sql);
			ps.setLong(1, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(coon, ps, null);
		}
	}
	
	@Override
	public void update(Long id, Student stu) {
		String sql = "UPDATE t_student SET name = ?, age = ? WHERE id = ?";
		Connection coon = null;
		PreparedStatement ps = null;
		try {
			coon = JdbcUtil.getConn();
			ps = coon.prepareStatement(sql);
			ps.setString(1, stu.getName());
			ps.setInt(2, stu.getAge());
			ps.setLong(3, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(coon, ps, null);
		}
	}

	@Override
	public Student get(Long id) {
		String sql = "SELECT * FROM t_student WHERE id = ?";
		Connection coon = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			coon = JdbcUtil.getConn();
			ps = coon.prepareStatement(sql);
			ps.setLong(1, id);
			rs = ps.executeQuery();
			if (rs.next()) {
				Student stu = new Student();
				stu.setId(rs.getLong("id"));
				stu.setName(rs.getString("name"));
				stu.setAge(rs.getInt("age"));
				return stu;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(coon, ps, rs);
		}
		return null;
	}

	@Override
	public List<Student> list() {
		
		String sql = "SELECT * FROM t_student";
		Connection coon = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			coon = JdbcUtil.getConn();
			ps = coon.prepareStatement(sql);
			rs = ps.executeQuery();
			List<Student> list = new ArrayList<>();
			while (rs.next()) {
				Student stu = new Student();
				stu.setId(rs.getLong("id"));
				stu.setName(rs.getString("name"));
				stu.setAge(rs.getInt("age"));
				list.add(stu);
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtil.close(coon, ps, rs);
		}
		return null;
	}

	

}
